import * as ol from "ol";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import TileLayer from "ol/layer/Tile";
import { Feature } from "ol";

/**
 * 图层管理类
 */
export default class LayerManager {
  // 用于临时存储图层信息
  private layers: Array<any> = []
  private map: ol.Map
  constructor(map: ol.Map) {
    this.map = map
  }

  /**
   * 添加图层
   * @param vectorLayer 图层源
   * @param layerId 图层标识
   */
  public addLayer(vectorLayer: VectorLayer | TileLayer | any, layerId: string, isAllowDelete: boolean) {
    if (this.getLayerById(layerId) !== null) {
      console.warn("图层已存在，请勿重复添加！")
      return
    }
    this.layers.push({ id: layerId, vectorLayer: vectorLayer, isAllowDelete })
    vectorLayer.set("id", layerId)
    this.map.addLayer(vectorLayer)

  }

  /**
   * 移除图层
   * @param layerId 图层id
   */
  public removeLayer(layerId: string) {

    const layer = this.getLayerById(layerId)
    if (layer !== null) {
      try {
        let vectorSource = layer.getSource() as VectorSource
        if (vectorSource != null) {
          vectorSource.clear()// 清除现有特征元素
        }
        this.map.removeLayer(layer) // 清除图层

        // 删除本地缓存数据
        const deleteIndex = this.layers.findIndex(m => m.id == layerId)
        this.layers.splice(deleteIndex, 1)
      } catch (error) {
        this.map.removeLayer(layer) // 清除图层

        // 删除本地缓存数据
        const deleteIndex = this.layers.findIndex(m => m.id == layerId)
        this.layers.splice(deleteIndex, 1)
      }



    }
  }
  /**
   * 移除除区域底层外的全部图层
   */
  public removeAllLayer() {
    const layers = this.getTemporaryLayer()
    layers.forEach(layer => {
      if (layer.isAllowDelete) {
        this.removeLayer(layer.id)
      }
    })
  }

  /**
   * 防止深拷贝，可以预先获取临时全部图层+
   * @returns 临时全部的图层
   */
  private getTemporaryLayer(): Array<any> {
    let layers: Array<any> = []
    this.layers.forEach(layer => {
      layers.push(layer)
    })
    return layers
  }

  /**
   * 更改图层信息
   * @param layerId 图层id
   * @param newSource Feature或Feature数组
   * @param newStyle 新样式
   */
  public updateLayer(layerId: string, newSource: Feature | Feature[], newStyle?: any) {
    const layer = this.getLayerById(layerId)
    if (layer !== null) {
      let vectorSource = layer.getSource() as VectorSource
      vectorSource.clear() // 清除现有特征元素

      // 检查 newSource 是否为数组
      if (Array.isArray(newSource)) {
        newSource.forEach(feature => vectorSource.addFeature(feature))
      } else {
        vectorSource.addFeature(newSource)
      }

      // 更新样式（如果提供了新样式）
      if (newStyle) {
        layer.setStyle(newStyle)
      }
    }
  }


  /**
   *  根据图层id获取图层实例
   * @param layerId layer图层标识
   * @returns  返回一个图层实例
   */
  public getLayerById(layerId: string): VectorLayer {
    const layer_index = this.layers.findIndex(m => m.id == layerId)
    let layer_vector
    if (layer_index != -1) {
      layer_vector = this.layers[layer_index].vectorLayer
    } else {
      layer_vector = null
    }
    return layer_vector
  }

  // 处理图层是否显示
  public setVisble(isShow: boolean, layerId: string) {
    const layer = this.getLayerById(layerId)
    if (layer != null) {
      layer.setVisible(isShow)
    }
  }

  // 修改图层透明度
  public setOpacity(layerId: string, opacity: number) {
    const layer = this.getLayerById(layerId)
    if (layer != null) {
      layer.setOpacity(opacity)
    }
  }
}
